package utils;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;

import com.example.administrator.newxlmedical.BaseEnterActivity;
import com.example.administrator.newxlmedical.MainActivity;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import beans.GoodsDetailsBean;
import beans.NewUserInfoBean;
import beans.PutAndDeleteBean;
import beans.StorageWarningBean;
import beans.StorageWarningInfoBean;
import beans.TimeoutBean;
import beans.UnusedGoodsBean;
import beans.UserInfoBean;
import beans.UserRightsBean;
import beans.WarningInfoBean;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import netframe.GetRetrofit;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import singleton.SingletonClass;

/**
 * Created by admin on 2017/12/20.
 */
public class HardwareInfoUtils {
    private SharedPreferences sharedPreferences;

    public static String getFingerprint() {
        return Build.FINGERPRINT;
    }

    public static String getMacAddress() {
        String macAddress = null;
        StringBuffer buf = new StringBuffer();
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("eth1");//网上的
//            networkInterface = NetworkInterface.getByName("eth0");
            if (networkInterface == null) {
                networkInterface = NetworkInterface.getByName("wlan0");
            }
            if (networkInterface == null) {
                return "02:00:00:00:00:02";
            }
            byte[] addr = networkInterface.getHardwareAddress();
            for (byte b : addr) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
        } catch (SocketException e) {
            e.printStackTrace();
            return "02:00:00:00:00:02";
        }
        return macAddress;
    }

    //获取机器码(本项目专用)
//    public static String getMachineCode(){
//      return   ActivityUtil.getMD5(ActivityUtil.getMD5( getFingerprint()+getMacAddress()));
//    }

    public static String getMachineCode(Context context) {
        String string = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);

        return string;
    }

    private boolean isTimeout = false;
    private boolean isWarning = false;
    private boolean isReturn = false;

    private int timeOutCount = 0;
    private int inventoryWarnCount = 0;
    private int returnHintCount = 0;
    private List<StorageWarningInfoBean> warnList = new ArrayList<>();
    private List<WarningInfoBean.DataBean> data = new ArrayList<>();
    private List<StorageWarningInfoBean> lessList;
    private StringBuilder sbUserIds = new StringBuilder();
    private String goodsId = "";
    private String terminalInfoId;
    private String starDate;
    private String endDate;
    private String cabinetInfoIds;
    private NewUserInfoBean.DataBean bean;
    private long startime = 0;
    private long endtime = 0;
    public Map<Integer, String> hashMap = new HashMap<>();
    private StringBuffer sb = new StringBuffer();
    private MyHandler allHandler = SingletonClass.getSingleton(MyHandler.class);

    public void getRedDotCount(Context context) {
        startime = System.currentTimeMillis();
        terminalInfoId = NetAddress.terminalInfoId;
        sharedPreferences = ActivityUtil.getSharedPreferences(context);
        Object o = ObjectSaveUtil.readObject(context, Constants.CABINETINFO_LOGICNUMBER_HASHMAP, Constants.CABINETINFO_LOGICNUMBER_HASHMAP);

        sb.delete(0, sb.length());
        if (o != null) {
            hashMap = (Map<Integer, String>) o;
            Set set = hashMap.entrySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Map.Entry mapentry = (Map.Entry) iterator.next();
                sb.append("'" + mapentry.getKey() + "',");
            }
            sb.deleteCharAt(sb.length() - 1);
        }

        loadTimeOut(context);
        loadInventoryWarn(context);
        loadReturnHint(context);

//        Intent intent = new Intent(context, MainActivity.class);
//        intent.putExtra(Constants.TIMEOUT_COUNT, timeOutCount);
//        intent.putExtra(Constants.INVENTORY_COUNT, inventoryWarnCount);
//        intent.putExtra(Constants.RETURNHINT_COUNT, returnHintCount);
//        context.startActivity(intent);
//        ActivityControl.finishAll();

    }

    private void loadInventoryWarn(Context context) {
        postData(context);
    }

    private void loadReturnHint(Context context) {
        loadingTask(context);
    }

    private void loadTimeOut(final Context context) {
        Log.e("aaa", "loadTimeOut: " + sb.toString());
        String sql = "select * from GoodsDetails where CabinetInfoId in (" + sb.toString() + ") and DATEADD(dd,-90,LastTime) < getdate() and Status = 3";
        Call<ArrayList<GoodsDetailsBean>> call = GetRetrofit.getInstance().getGoodsDetails(NetAddress.token, NetAddress.machineCode, sql);
        call.enqueue(new Callback<ArrayList<GoodsDetailsBean>>() {
            @Override
            public void onResponse(Call<ArrayList<GoodsDetailsBean>> call, Response<ArrayList<GoodsDetailsBean>> response) {
                ArrayList<GoodsDetailsBean> body = response.body();
                if (body != null) {
                    timeOutCount = body.size();
                } else {
                    timeOutCount = 0;
                }
                        isTimeout = true;
                Log.e("CCC", "onResponse: " + timeOutCount);
                if (isWarning && isReturn) {
                    endtime = System.currentTimeMillis();
                    Log.e("TAG", "onResponse: loadTimeOut  " + (endtime - startime));
                    jump2Main(context);
                }
            }

            @Override
            public void onFailure(Call<ArrayList<GoodsDetailsBean>> call, Throwable t) {
                isTimeout = true;
                if (isWarning && isReturn) {
                    endtime = System.currentTimeMillis();
                    Log.e("TAG", "onResponse: loadTimeOut  " + (endtime - startime));
                    jump2Main(context);

                }
                ToastUtil.showToast(context, t.getMessage());
            }
        });
    }

    private void postData(final Context context) {
        GetRetrofit.getInstance().getWarningGoods(NetAddress.token, NetAddress.machineCode, NetAddress.deptCode)
                .enqueue(new Callback<WarningInfoBean>() {
                    @Override
                    public void onResponse(Call<WarningInfoBean> call, Response<WarningInfoBean> response) {
                        warnList.clear();
                        WarningInfoBean body = response.body();
                        if (body != null) {
                            data = body.getData();
                            sbUserIds.delete(0, sbUserIds.length());
                            if (data != null && data.size() != 0) {
                                for (int i = 0; i < data.size(); i++) {
                                    WarningInfoBean.DataBean dataBean = data.get(i);
                                    sbUserIds.append(dataBean.getGID() + ",");
                                    StorageWarningInfoBean bean = new StorageWarningInfoBean();
                                    bean.setGoodsName(dataBean.getGoodName());
                                    bean.setNumber(dataBean.getCount() + "");
                                    bean.setUnit(dataBean.getGoodsUnit());
                                    bean.setSupplier(dataBean.getManufacturer());
                                    bean.setSpecification(dataBean.getSpecification());
                                    bean.setWarnCount("0");
                                    bean.setGID(dataBean.getGID() + "");
                                    warnList.add(bean);
                                }
                                goodsId = sbUserIds.deleteCharAt(sbUserIds.length() - 1).toString();
                                getData(context);

                            } else {
                                isWarning = true;
                                inventoryWarnCount = 0;
                                endtime = System.currentTimeMillis();
                                if (isTimeout && isReturn) {
                                    Log.e("TAG", "onResponse:postData []  " + (endtime - startime));
                                    jump2Main(context);

                                }
                                NetAddress.INVENTORY_COUNT = inventoryWarnCount;
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<WarningInfoBean> call, Throwable t) {
                        isWarning = true;
                        ToastUtil.showToast(context, t.getMessage());
                    }
                });
    }

    private void getData(final Context context) {
        GetRetrofit.getInstance().getStorageWarning1(NetAddress.token, NetAddress.machineCode, "select * from StorageWarning where TerminalInfoId =" + NetAddress.terminalInfoId)
                .enqueue(new Callback<List<StorageWarningBean>>() {
                    @Override
                    public void onResponse(Call<List<StorageWarningBean>> call, Response<List<StorageWarningBean>> response) {
                        List<StorageWarningBean> body = response.body();
//                        ToastUtil.showToast(InventoryWarningActivity.this,response.code()+"");
                        if (body != null && body.size() > 0) {
                            for (int j = 0; j < body.size(); j++) {
                                int count = 0;
                                StorageWarningBean warningBean = body.get(j);
                                for (int i = 0; i < warnList.size(); i++) {
                                    StorageWarningInfoBean storageWarningInfoBean = warnList.get(i);
                                    if (Integer.parseInt(storageWarningInfoBean.getGID()) == warningBean.getGoodsInfoId()) {
                                        count++;
                                        if (Integer.parseInt(storageWarningInfoBean.getNumber()) <= warningBean.getWarningCount()) {
                                            inventoryWarnCount++;
                                        }
                                        break;
                                    }
                                }
                                if (count == 0 && warningBean.getWarningCount() != 0) {
                                    inventoryWarnCount++;
                                }
                            }
                        }

                        isWarning = true;
                        Log.e("CCC", "onResponse: " + timeOutCount);
                        if (isTimeout && isReturn) {
                            endtime = System.currentTimeMillis();
                            Log.e("TAG", "onResponse: getData  " + (endtime - startime));
                            jump2Main(context);
                        }
                    }

                    @Override
                    public void onFailure(Call<List<StorageWarningBean>> call, Throwable t) {
                        isWarning = true;
                        if (isTimeout && isReturn) {
                            endtime = System.currentTimeMillis();
                            Log.e("TAG", "onResponse: getData  " + (endtime - startime));
                            jump2Main(context);
                        }
                        ToastUtil.showToast(context, t.getMessage());
                        Log.e("TAG", "onResponse: getData  onFailure");
                    }
                });
    }

    private void loadingTask(final Context context) {

        bean = (NewUserInfoBean.DataBean) ObjectSaveUtil.readObject(context, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);
        int id = bean.getID();
        int roleId = bean.getRoleInfoId();
        if (roleId == Constants.ROLE_HEAD_NURSE || roleId == Constants.ROLE_MANAGE || roleId == Constants.ROLE_FACTORY) {
            id = 0;
        }
        GetRetrofit.getInstance().getUnusedGoods(NetAddress.token, NetAddress.machineCode, NetAddress.deptCode, id + "", "2")
                .enqueue(new Callback<UnusedGoodsBean>() {
                    @Override
                    public void onResponse(Call<UnusedGoodsBean> call, Response<UnusedGoodsBean> response) {
                        sbUserIds.delete(0, sbUserIds.length());
                        UnusedGoodsBean data = response.body();
                        List<UnusedGoodsBean.DataBean> body = data.getData();
                        if (body != null) {
                            returnHintCount = body.size();
                        } else {
                            returnHintCount = 0;
                        }
                        loadingTask1(context);
                    }

                    @Override
                    public void onFailure(Call<UnusedGoodsBean> call, Throwable t) {
                        loadingTask1(context);
                        ToastUtil.showToast(context, t.getMessage());
                        Log.e("TAG", "onResponse: loadingTask  onFailure");
                        Log.e("TAG", "onResponse: " + t.getMessage());
                    }
                });
    }

    private void loadingTask1(final Context context) {

        bean = (NewUserInfoBean.DataBean) ObjectSaveUtil.readObject(context, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);
        int id = bean.getID();
        int roleId = bean.getRoleInfoId();
        if (roleId == Constants.ROLE_HEAD_NURSE || roleId == Constants.ROLE_MANAGE || roleId == Constants.ROLE_FACTORY) {
            id = 0;
        }
        GetRetrofit.getInstance().getUnusedGoods(NetAddress.token, NetAddress.machineCode, NetAddress.deptCode, id + "", "1")
                .enqueue(new Callback<UnusedGoodsBean>() {
                    @Override
                    public void onResponse(Call<UnusedGoodsBean> call, Response<UnusedGoodsBean> response) {
                        sbUserIds.delete(0, sbUserIds.length());
                        UnusedGoodsBean data = response.body();
                        List<UnusedGoodsBean.DataBean> body = data.getData();
                        isReturn = true;
                        if (body != null) {
                            returnHintCount += body.size();
                        } else {
                            returnHintCount += 0;
                        }
                        endtime = System.currentTimeMillis();
                        NetAddress.RETURNHINE_COUNT = returnHintCount;
                        if (isTimeout && isWarning) {
                            Log.e("TAG", "onResponse: loadingTask  " + (endtime - startime));
                            jump2Main(context);
                        }
                    }

                    @Override
                    public void onFailure(Call<UnusedGoodsBean> call, Throwable t) {
                        isReturn = true;
                        ToastUtil.showToast(context, t.getMessage());
                        Log.e("TAG", "onResponse: loadingTask  onFailure");
                        Log.e("TAG", "onResponse: " + t.getMessage());
                    }
                });
    }

    private void jump2Main(Context context) {
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putInt(Constants.TIMEOUT_COUNT,timeOutCount);
        edit.putInt(Constants.INVENTORY_COUNT,inventoryWarnCount);
        edit.putInt(Constants.RETURNHINT_COUNT,returnHintCount);
        edit.commit();
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
        ActivityControl.finishAll();
    }

}
